package com.yunji.web.system;

import com.google.common.collect.Maps;
import com.yunji.base.cache.BaseCache;
import com.yunji.common.annotation.Log;
import com.yunji.common.base.BaseController;
import com.yunji.common.base.RuoYiConfig;
import com.yunji.common.base.response.Response;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.enums.common.BusinessType;
import com.yunji.common.model.domain.SysUserDO;
import com.yunji.common.model.dto.LoginInfo;
import com.yunji.common.utils.SecurityUtils;
import com.yunji.common.utils.StringUtils;
import com.yunji.common.utils.file.FileUploadUtils;
import com.yunji.common.utils.file.MimeTypeUtils;
import com.yunji.system.context.SystemContext;
import com.yunji.system.service.ISysUserService;
import com.yunji.system.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 个人信息 业务处理
 *
 * @author ruoyi
 */
@Api("个人信息业务处理")
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 个人信息
     */
    @ApiOperation("个人信息")
    @GetMapping
    public Response<Map<String,Object>> profile() {
        LoginInfo loginUser = SystemContext.getUser();
        SysUserDO user = BaseCache.getUser(loginUser.getUserId());
        Map<String, Object> map = Maps.newHashMap();
        map.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        map.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        map.put("user",user);
        return ResponseHelper.success(map);
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public Response<String> updateProfile(@RequestBody SysUserDO user) {
        LoginInfo loginUser = SystemContext.getUser();
        SysUserDO currentUser =  BaseCache.getUser(loginUser.getUserId());
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhonenumber(user.getPhonenumber());
        currentUser.setUserName(user.getPhonenumber());
        currentUser.setSex(user.getSex());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(currentUser)) {
            return ResponseHelper.failure("修改用户'" + loginUser.getUsername() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getUserName()) && !userService.checkUserNameUnique(currentUser)) {
            return ResponseHelper.failure("修改用户'" + loginUser.getUsername() + "'失败，账号");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser)) {
            return ResponseHelper.failure("修改用户'" + loginUser.getUsername() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(currentUser) > 0) {
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
            return ResponseHelper.success();
        }
        return ResponseHelper.failure("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    @PreAuthorize("@ss.hasPermi('system:subUser:resetPwd')")
    public Response<String> updatePwd(String oldPassword, String newPassword) {
        LoginInfo loginUser = SystemContext.getUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return ResponseHelper.failure("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return ResponseHelper.failure("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(userName, newPassword) > 0) {
            // 更新缓存用户密码
           // loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return ResponseHelper.success();
        }
        return ResponseHelper.failure("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @ApiOperation("头像上传")
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public  Response<Map<String,Object>> avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            LoginInfo loginUser = SystemContext.getUser();
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("imgUrl", avatar);
                // 更新缓存用户头像
               // loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ResponseHelper.success(map);
            }
        }
        return ResponseHelper.failure("上传图片异常，请联系管理员");
    }
}
